import { Body, Controller, Get, HttpCode, Post, Request } from '@nestjs/common'
import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger'
import * as Useragent from 'useragent'
import { ClientInfoDto, LoginDto } from './dto'
import { MainService } from './main.service'

@ApiTags('根目录')
@Controller('/')
export class MainController {
  constructor(private readonly mainService: MainService) {}

  @ApiOperation({ summary: '用户登录', description: '联调人：xxx' })
  @ApiBody({ type: LoginDto, required: true })
  @Post('/login')
  @HttpCode(200)
  login(@Body() user: LoginDto, @Request() req) {
    const agent = Useragent.parse(req.headers['user-agent'])
    const os = agent.os.toJSON().family
    const browser = agent.toAgent()
    const clientInfo = {
      userAgent: req.headers['user-agent'],
      ipaddr: req.ip,
      browser: browser,
      os: os,
      loginLocation: ''
    }
    return this.mainService.login(user, clientInfo)
  }

  @ApiOperation({ summary: '用户信息' })
  @Get('/getInfo')
  async getInfo(@Request() req) {
    const user = req.user
    return {
      msg: '操作成功',
      code: 200,
      permissions: user.permissions,
      roles: user.roles || ['admin'],
      user: user.user
    }
  }

  @ApiOperation({ summary: '退出登录' })
  @ApiBody({ type: LoginDto, required: true })
  @Post('/logout')
  @HttpCode(200)
  async logout(@Request() req) {
    const agent = Useragent.parse(req.headers['user-agent'])
    const os = agent.os.toJSON().family
    const browser = agent.toAgent()
    const clientInfo = {
      ipaddr: req.ip,
      browser: browser,
      os: os,
      loginLocation: ''
    }
    return this.mainService.logout(clientInfo as ClientInfoDto)
  }

  @ApiOperation({ summary: '获取验证图片' })
  @Get('captchaImage')
  captchaImage() {
    return {
      captchaEnabled: false,
      code: 200,
      msg: '操作成功'
    }
  }

  @ApiOperation({ summary: '路由信息' })
  @Get('getRouters')
  getRouters(@Request() req) {
    const userId: string = req.user.user.userId
    return this.mainService.getRouters(+userId)
  }
}
